<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Examination extends My_Controller {

    public function __construct()
    {
         parent::__construct();
         $this->load->model('Examination_model', 'examination');
         $this->load->model("News_model","news");
		 $this->load->model("Point_model","point");
    }

    public function questionList()
    {
        $params['id'] = $this->queryData['id'];
        $validate = new Validate([
            'id' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
		$activity_endtime = $this->news->getNewsDetail($params['id'],'activity_endtime')['activity_endtime'];
		if (date("YmdHis",$activity_endtime) < date("YmdHis",time())) {
            $this->errorCode = 80004;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $fields = " ques.newsID,ques.questionID ,ques.questionTitle,ques.questionType,ques.CreateTime,ques.answer,ques.single_question_point,news.all_question_point";
        $questionList = $this->examination->getQuestionList($params['id'],$fields);
        $userInfo = $this->userDetail;
        $result = ['all_question_point'=>0,'questionList'=>[]];
        foreach ($questionList as $key => $value) {
          $result['all_question_point'] = $value['all_question_point'];
        
          if($userInfo)
          {
    			$questionList[$key]['answerInfo'] = [];
				$questionList[$key]['answerInfo']['answer'] = $value['answer'];
				
    			
    			$data = [
    				'newsID'=>$params['id'],
    				'AccountID'=>$userInfo['AccountID'],
    				'questionID'=>$value['questionID']
    			];
    			$questionList[$key]['answerInfo']['statue'] = $this->examination->hasAnswered($data);
			     $questionList[$key]['answerInfo']['isright'] = 0;
            $myAnswer = $this->examination->getMyAnswer($value['questionID'],$userInfo['AccountID']);
			
            $questionList[$key]['answerInfo']['myAnswer'] = $myAnswer['answer'];
			
			if($value['questionType'] == 3)
			{
				$questionList[$key]['answerInfo']['answer'] = $value['answer']?OSSHOST.$value['answer']:'';
				$questionList[$key]['answerInfo']['myAnswer'] = $myAnswer['answer']?OSSHOST.$myAnswer['answer']:'';
			}
            if($value['questionType'] == 1 || $value['questionType'] == 2){
                if($this->isright($value['answer'],$myAnswer['answer']))
                {
                  $questionList[$key]['answerInfo']['isright'] = 1;
                }
            }elseif ($value['questionType'] == 3 && $myAnswer['answer'] == 1) {
               $questionList[$key]['answerInfo']['isright'] = 1;
            }
            //$questionList[$key]['isright'] = $this->examination->isright($value['questionID'],$value['questionType'],$userInfo['AccountID']);
          }
		  unset($questionList[$key]['isDel'],$questionList[$key]['answer'],$questionList[$key]['all_question_point']);
          if($value['questionType'] == 1)
          {
            $optionList = $this->examination->getOptionList($value['questionID']);
            $questionList[$key]['option'] = $optionList;
          }
          
        }
        $result['questionList'] = $questionList;
        $this->createApi($result);exit;
    }

    public function activityList()
    {
      $this->isArrays = true;
      $params['per_page'] = $this->queryData['per_page'];
      $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
      $limit  = $this->config->item('limit');
      $fields = " questionID, questionTitle, questionType,newsID,CreateTime";
      $questionList = $this->examination->getExaminationList($params['per_page'], $limit, $fields);
      $userInfo = $this->userDetail;
      $params['AccountID'] = $userInfo['AccountID'];
      foreach($questionList as $key=>$value)
      {
        $questionList[$key]['statue'] = 0;
        if($userInfo)
        {
		$answerData = ['AccountID'=>$userInfo['AccountID'],'questionID'=>$value['questionID'],'newsID'=>$value['newsID']];
          $questionList[$key]['statue'] = $this->examination->hasAnswered($answerData);
        }
        
        $newsDetail = $this->news->getNewsDetail($value['newsID'],"cover");
          $questionList[$key]['cover'] = $newsDetail['cover']?OSSHOST.$newsDetail['cover']:'';
      }
      $this->createApi($questionList);exit;
    }

    public function answer()
    {
		
		$params['newsID'] = $this->queryData['newsID'];;
		$params['questionID'] = $this->queryData['questionID'];;
		$params['answer'] = $this->queryData['answer'];;
		$params['questionType'] = $this->queryData['questionType'];;

		$validate = new Validate([
			'questionID' => 'require|number',
			'answer' => 'require|string',
     	    'newsID' => 'require|number',
			'questionType' => 'require|number',
		]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
		$result = [
			'isright'=>-1,
			'single_question_point'=>0,
			'single_question_money'=>0,
			'allRightPoint'=>0,
			'allRightMoney'=>0,		
			];
		$params['AccountID'] = $this->userDetail['AccountID'];
		//查询题目是否存在
		$questionInfo = $this->examination->getQuestionInfo($params['questionID'],$params['newsID'],$params['questionType']);
		if(!$questionInfo)
		{
			$this->errorCode = 80002;
            $this->createApi();exit;
		}
		if($questionInfo['activity_endtime']<time())
		{
			$this->errorCode = 80004;
            $this->createApi();exit;
		}
		$totalMoney = $this->examination->getTotalMoneyByNewsID($params['newsID']);
		if($questionInfo['totalmoney'] < ($totalMoney+$questionInfo['single_question_money']))
		{
			$this->errorCode = 90009;
            $this->createApi();exit;
		}

		//检测是否答过题目
		$hasanswered = $this->examination->checkQuestionAnswered($params['questionID'],$params['AccountID']);
		if(!empty($hasanswered))
		{
			$this->errorCode = 80001;
            $this->createApi();exit;
		}

		$answerData['questionID'] = $params['questionID'];
		$answerData['answer'] = $params['answer'];
		$answerData['newsID'] = $params['newsID'];
		$answerData['AccountID'] = $params['AccountID'];
		$answerData['Createtime'] = date("Y-m-d H:i:s",time());
		
		if($this->isright((string)$questionInfo['answer'],(string)$params['answer'])){
			$result['isright'] = 1;
		}
		if(in_array($params['questionType'],[1,2]))
		{
			if($result['isright'] == -1)
			{
				
				$this->createApi(['isright'=>$result['isright']]);exit;
			}
			$answerData['isright'] = 1;
			
		}
		$answerID = $this->examination->answer($answerData);
		//单选填空添加积分
		if($answerID)
        {
            if($params['questionType'] == 1 || $params['questionType'] == 2){
                if($this->isright((string)$questionInfo['answer'],(string)$params['answer']))
                {
					 //添加积分
					if($questionInfo['single_question_point'])
					{
						$pointData = [
							'points'=>$questionInfo['single_question_point'],
							'AccountID'=>$params['AccountID'],
							'type'=>6,
							'createtime'=>date("Y-m-d",time()),
							'typeid'=>$params['questionID'],
						];		
						$res = $this->point->addAnswerPoints($pointData);
						if(!$res)
						{
							$this->errorCode = 50006;
							$this->createApi();exit;
						}
						if($questionInfo['all_question_point'])
						{
								$data['content'] = $this->userDetail['nickname']."获得答题".$questionInfo['single_question_point']."积分奖励";
								$this->point->addCarousel($data);
						}
						$result['single_question_point'] = $questionInfo['single_question_point'];
					}
					
										 //添加金钱
					if($questionInfo['single_question_money'])
					{
						$pointData = [
							'money'=>$questionInfo['single_question_money'],
							'AccountID'=>$params['AccountID'],
							'type'=>6,
							'createtime'=>date("Y-m-d",time()),
							'typeid'=>$params['questionID'],
						];		
						$res = $this->point->addAnswerMoney($pointData);
						if(!$res)
						{
							$this->errorCode = 50006;
							$this->createApi();exit;
						}
						if($questionInfo['all_question_money'])
						{
							$data['content'] = $this->userDetail['nickname']."获得答题".$questionInfo['single_question_money']."元现金奖励";
							$this->point->addCarousel($data);
						}
						$result['single_question_money'] = $questionInfo['single_question_money'];
					}
					
                }
            }
			
			//判断每一道题是不是对的
			$fields = " ques.newsID,ques.questionID ,ques.questionTitle,ques.questionType,ques.CreateTime,ques.answer,ques.single_question_point,news.all_question_point";
			$questionList = $this->examination->getQuestionList($params['newsID'],$fields);
			$allRight = 1;
			foreach($questionList as $qkey=>$value)
			{
				$answerInfo = $this->examination->checkQuestionAnswered($value['questionID'],$params['AccountID']);
				if(empty($answerInfo) || $answerInfo['isright'] != 1)
				{
					$allRight = 0 ;					
				}
			}
			if($allRight == 1)
			{
				 //添加积分
				$pointData = [
					'points'=>$questionInfo['all_question_point'],
					'AccountID'=>$params['AccountID'],
					'type'=>6,
					'createtime'=>date("Y-m-d",time()),
					'typeid'=>$params['questionID'],
				];		
				$res = $this->point->addAnswerPoints($pointData);
				if($questionInfo['all_question_point'])
				{
					$result['allRightPoint'] = $questionInfo['all_question_point'];
					$data['content'] = $this->userDetail['nickname']."获得全部答题".$questionInfo['all_question_point']."积分奖励";
				}
				
				$this->point->addCarousel($data);
				
				 //添加积分
				$pointData = [
					'money'=>$questionInfo['all_question_money'],
					'AccountID'=>$params['AccountID'],
					'type'=>6,
					'createtime'=>date("Y-m-d",time()),
					'typeid'=>$params['questionID'],
				];		
				$res = $this->point->addAnswerMoney($pointData);
				if($questionInfo['all_question_point'])
				{
					$data['content'] = $this->userDetail['nickname']."获得全部答题".$questionInfo['all_question_money']."元现金奖励";
					$this->point->addCarousel($data);
				}
				$result['allRightMoney'] = $questionInfo['all_question_money'];
			}
			
        }else{
			$this->errorCode = 50006;
			$this->createApi();exit;
		}
		$result['isright'] = (int)$result['isright'];
        $this->createApi($result);
    }

    /**
     * 判断题目是否正确
     */
    public function isright($myAnswer,$rightRnswer)
    {
    	if(strpos($myAnswer,$rightRnswer) !== false)
    	{
    		return true;
    	}
    	if(strpos($rightRnswer,$myAnswer) !== false)
    	{
    		return true;
    	}
    	return false;
    }

    public function delete()
    {
    	$params['newsID'] = $this->queryData['newsID'];
        $validate = new Validate([
            'newsID' => 'require|number',
        ]);

        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $userInfo = $this->userDetail;
        $params['AccountID'] = $userInfo['AccountID'];
        $res = $this->examination->deleteActivity($params);
        if(!$res){
            $this->errorCode = 50006;
        }
        $this->createApi();
    }
}

/* End of file region.php */
/* Location: ./application/controllers/region.php */
